package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.entity.Shop;
import com.antdesignbackend.backend.entity.UserRoles;
import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.entity.entityVo.ShopVo;
import com.antdesignbackend.backend.entity.entityVo.UsersVo;
import com.antdesignbackend.backend.service.IShopService;
import com.antdesignbackend.backend.service.UserRolesService;
import com.antdesignbackend.backend.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/regionalPartner")
public class RegionalPartnerController {
    private Integer menuId;
    private Integer userId;
    private String roleID;
    ReturnVO result = new ReturnVO();
    @Autowired
    private IShopService shopService;
    @Autowired
    UserService userService;
    @Autowired
    UserRolesService userRolesService;

    /**
     * 区域合伙人首页
     */
    @GetMapping("/index")
    @AuthToken
    public String index(String menuId, HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "regionalPartner/index";
    }
    /**
     * 商户首页
     */
    @GetMapping("/merchants")
    @AuthToken
    public String merchants(String menuId, HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "user/merchants";
    }
    /***
     * 前端分页查询
     *
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody UsersVo data, HttpServletRequest request) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        result = new ReturnVO();
        List<UsersVo> datalist=new ArrayList<>();
        QueryWrapper<UsersVo> wrapper =new QueryWrapper<UsersVo>();
        //根据权限生成过滤条件
        if(roleID.equals("1")){//管理员
        }else{//商户
            wrapper.inSql("userId","select userid from users where Activity=1 and UserID="+userId);
        }
        //正常查询过滤条件
        if(data.getUserName()!=null && !data.getUserName().equals(""))
        {
            wrapper.and(wra -> wra.like("userName", data.getUserName()));
        }
        if(data.getTypes()!=null && !data.getTypes().equals(""))
        {
            wrapper.and(wra -> wra.eq("types", data.getTypes()));
        }
        wrapper.eq("userType","2");
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=userService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0)
        {
            datalist= userService.searchs(wrapper.orderByAsc("userName"),new Page<>(data.getPageIndex(),data.getPageSize()));
            //得到当前菜单具备的功能权限
            //List<Button> list = permissionService.filterPermission(String.valueOf(roleID), menuId);
            //datalist.forEach(model -> model.setButtonList(list));
        }
        result.setData(datalist);
        return result;
    }
    /***
     * 新增/修改保存
     * id 0是新增加，否则修改
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    @AuthToken
    public ReturnVO save(@RequestBody UsersVo vo) throws Exception {
        result = new ReturnVO();
        boolean b = false;
        Users entity = new Users();
        if(vo.getUserID()>0)
        {
            //先获取旧的数据集
            entity= userService.getById(vo.getUserID());
        }
        if(vo.getAction().equals("change")){
            entity.setTypes(vo.getTypes());
            /*entity.setParentID(1);
            //修改角色权限表
            QueryWrapper<UserRoles> rolesQueryWrapper =new QueryWrapper<UserRoles>();
            rolesQueryWrapper.eq("userID",entity.getUserID());
            UserRoles userRoles=new UserRoles();
            userRoles.setUserID(entity.getUserID());
            userRoles.setRoleID(2);
            userRolesService.update(userRoles,rolesQueryWrapper);*/
        }else {
            //新增，修改
            entity.setUserName(vo.getUserName());
            entity.setCreateDateTime(vo.getCreateDateTime());
            entity.setPhone(vo.getPhone());
            entity.setUserType(2);
        }
        if (vo.getUserID() == 0) {
            //新增
            entity.setTypes(0);
            entity.setActivity(1);
            entity.setAmount(0.0);
            b = userService.save(entity);
        }
        else{
            //修改
            b = userService.updateById(entity);
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        }
        else
        {
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    /***
     * 根据id删除
     */
    @DeleteMapping("/deleteById/{id}")
    @ResponseBody
    public ReturnVO deleteById(@PathVariable Serializable id) {
        result = new ReturnVO();
        if (userService.removeById(Integer.parseInt(id.toString())) == true) {
            result.setMessage("删除成功");
            result.setCode("200");
        } else {
            result.setMessage("删除失败");
            result.setCode("500");
        }
        return result;
    }
    /***
     * 前端分页查询
     *
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/merchantsSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO merchantsSearch(@RequestBody UsersVo data, HttpServletRequest request) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        result = new ReturnVO();
        List<UsersVo> datalist=new ArrayList<>();
        QueryWrapper<UsersVo> wrapper =new QueryWrapper<UsersVo>();
        //根据权限生成过滤条件
        if(roleID.equals("1")){//管理员
        }else{//商户
            wrapper.inSql("userId","select userid from users where Activity=1 and UserID="+userId);
        }
        //正常查询过滤条件
        if(data.getUserName()!=null && !data.getUserName().equals(""))
        {
            wrapper.and(wra -> wra.like("userName", data.getUserName()));
        }
        if(data.getTypes()!=null && !data.getTypes().equals(""))
        {
            wrapper.and(wra -> wra.eq("types", data.getTypes()));
        }
        wrapper.eq("userType","4");
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=userService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0)
        {
            datalist= userService.searchs(wrapper.orderByAsc("userName"),new Page<>(data.getPageIndex(),data.getPageSize()));
            //得到当前菜单具备的功能权限
            //List<Button> list = permissionService.filterPermission(String.valueOf(roleID), menuId);
            //datalist.forEach(model -> model.setButtonList(list));
        }
        result.setData(datalist);
        return result;
    }
    /***
     * 新增/修改保存
     * id 0是新增加，否则修改
     * @return
     */
    @PostMapping("/merchantsSave")
    @ResponseBody
    @AuthToken
    public ReturnVO merchantsSave(@RequestBody UsersVo vo) throws Exception {
        result = new ReturnVO();
        boolean b = false;
        Users entity = new Users();
        if(vo.getUserID()>0)
        {
            //先获取旧的数据集
            entity= userService.getById(vo.getUserID());
        }
        if(vo.getAction().equals("change")){
            entity.setTypes(vo.getTypes());
            /*entity.setParentID(1);
            //修改角色权限表
            QueryWrapper<UserRoles> rolesQueryWrapper =new QueryWrapper<UserRoles>();
            rolesQueryWrapper.eq("userID",entity.getUserID());
            UserRoles userRoles=new UserRoles();
            userRoles.setUserID(entity.getUserID());
            userRoles.setRoleID(2);
            userRolesService.update(userRoles,rolesQueryWrapper);*/
        }else {
            //新增，修改
            entity.setUserName(vo.getUserName());
            entity.setCreateDateTime(vo.getCreateDateTime());
            entity.setPhone(vo.getPhone());
            entity.setUserType(4);
        }
        if (vo.getUserID() == 0) {
            //新增
            entity.setTypes(0);
            entity.setActivity(1);
            entity.setAmount(0.0);
            b = userService.save(entity);
        }
        else{
            //修改
            b = userService.updateById(entity);
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        }
        else
        {
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }

}
